package com.se.controller;

import cn.hutool.core.util.StrUtil;
import com.se.domain.dto.page.PageDTO;
import com.se.domain.request.param.SearchActParam;
import com.se.domain.vo.ResultVO;
import com.se.domain.vo.SearchActItemVO;
import com.se.domain.vo.SearchActListVO;
import com.se.enums.ResultCode;
import com.se.exception.ResultException;
import com.se.global.AuthHeaderRequestWrapper;
import com.se.service.ActSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.List;

@RestController
@Validated
public class ActSearchController {

    @Autowired
    ActSearchService actSearchService;
    @PostMapping("/must/act/search")
    public ResultVO<SearchActListVO> searchAct(
            @RequestHeader(AuthHeaderRequestWrapper.USER_ID_HEADER_NAME) Long userId,
            @RequestBody @Validated SearchActParam searchActParam
    ) throws IOException, ResultException {
        this.checkSearchActParam(searchActParam);

        List<SearchActItemVO> itemVOS = actSearchService.searchAct(searchActParam, userId);
        SearchActListVO vo = new SearchActListVO();
        vo.setList(itemVOS);
        vo.setPage(new PageDTO(searchActParam.getPage().getPage(), itemVOS.size()));

        return ResultVO.ok(vo);
    }
    private void checkSearchActParam(SearchActParam searchActParam) throws ResultException {
        //key 为空字串则置空
        if(StrUtil.isBlank(searchActParam.getKey())){
            searchActParam.setKey(null);
        }

        //判断sort与desc
        if(searchActParam.getSort() != null){
            searchActParam.setSort(searchActParam.getSort().trim());
            switch (searchActParam.getSort()){
                case "" -> {}
                case "start", "end" -> {
                    if(searchActParam.getDesc() == null){
                        throw new ResultException(ResultCode.PARAM_INVALID.getCode(), "sort字段不为空时desc不能为空");
                    }
                }
                default -> throw new ResultException(ResultCode.PARAM_INVALID.getCode(), "sort字段错误");
            }
        }

    }
}
